package server;

import org.json.java.JSONException;
import org.json.java.JSONObject;

import java.io.*;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Created by IntelliJ IDEA.
 * User: ryan
 * Date: 12/1/11
 * Time: 12:49 PM
 * To change this template use File | Settings | File Templates.
 */
public class ClientConnection implements Runnable{
    private String name;
    private final ChatServer chatServer;
    private final Socket socket;
    private BufferedReader in;

    public ClientConnection(Socket s, ChatServer chatServer) {

        this.chatServer=chatServer;
        this.socket=s;
        try{
            in =  new BufferedReader(new InputStreamReader(s.getInputStream()));
        }catch(IOException e){
            e.printStackTrace(System.err);
        }
        //get the name of this client
        name = "default";
    }

    public void run() {
        //read in the name
        JSONObject msg;
        try{
            Logger.getLogger(this.getClass().getName()).log(Level.INFO,"waiting for name");
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            name = br.readLine();
            Logger.getLogger(this.getClass().getName()).log(Level.INFO,"receivedName: "+name);
        }catch(IOException e){
            e.printStackTrace(System.err);
        }
        chatServer.addClient(socket,name);
        //receive a message, print it out to all others(including self)
        while(socket.isConnected()){
            Logger.getLogger(this.getClass().getName()).log(Level.INFO,"waiting for message from client "+name);
            msg = readMessage();
            if(msg!=null){
                try{
                Logger.getLogger(this.getClass().getName()).log(Level.INFO,"switching message "+name+":"+msg.toString());
                ChatServer.MESSAGE_TYPE type = ChatServer.MESSAGE_TYPE.valueOf(msg.getString("type"));
                if(type == ChatServer.MESSAGE_TYPE.CLIENTS){
                   Logger.getLogger(this.getClass().getName()).log(Level.INFO,"sending clients list "+name);
                   chatServer.sentAllClientsMsg(socket);
                }else{
                    //forward the message to all the clients;
                    chatServer.sendMessage(msg);
                }
                }catch(JSONException e){
                    e.printStackTrace(System.err);
                }
            }else{
                System.out.println("Null message.  Exiting ClientConnetion");
                break;
            }
            Thread.yield();
        }
        Logger.getLogger(this.getClass().getName()).log(Level.INFO,"client stopped "+this.name);
        chatServer.removeClient(socket,name);
    }

    public JSONObject readMessage(){
        try{
            String message = in.readLine();
            Logger.getLogger(this.getClass().getName()).log(Level.INFO,"receivedMessage: "+message);
            if(message==null){
                return null;
            }
            //return the completed message
            return new JSONObject(message);
        }catch(IOException e){
            e.printStackTrace(System.err);
        } catch (JSONException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        //Default to returning an empty string
        return null;
    }
}
